﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Web.Script.Serialization;
using System.Web;
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Net;
using System.Configuration;
using System.Diagnostics;
using System.Data.Odbc;
using System.Data;
using System.Data.OleDb;
using System.Security.Cryptography;
using System.Web.Http.ModelBinding;
using QRCoder;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Exceptions;

namespace Util
{
    public class Common
    {
        public static string[] path = HttpContext.Current.Request.Url.AbsoluteUri.Split('/');
        public static int PageSize = 20;
        public static Dictionary<int, string> OrderState = new Dictionary<int, string>(); //订单状态
        public static Dictionary<int, string> HouseOrderState = new Dictionary<int, string>(); //订单状态
        public static Dictionary<int, string> Position = new Dictionary<int, string>(); //广告位
        public static Dictionary<int, string> VideoType = new Dictionary<int, string>(); //视频类型
        public static Dictionary<int, string> Sex = new Dictionary<int, string>(); //性别
        public static Dictionary<int, string> TypeText = new Dictionary<int, string>(); //广告类别
        public static Dictionary<int, string> DouType = new Dictionary<int, string>(); //兔豆类别
        public static Dictionary<int, string> TakeCashState = new Dictionary<int, string>(); //提现状态
        public static Dictionary<int, string> TakeCashType = new Dictionary<int, string>(); //提现类型
        public static Dictionary<int, string> StockPayType = new Dictionary<int, string>(); //投资类型
        public static Dictionary<int, string> StockDivideType = new Dictionary<int, string>(); //分红方案
        public static Dictionary<int, string> PersonType = new Dictionary<int, string>(); //报名状态
        public static Dictionary<int, string> EasyState = new Dictionary<int, string>(); //核验状态
        public static Dictionary<int, string> ParkState = new Dictionary<int, string>(); //违章状态
        public static Dictionary<int, string> ParkType = new Dictionary<int, string>(); //违停类型
        public static Dictionary<int, string> SysName = new Dictionary<int, string>(); //系统类型
        public static Dictionary<int, string> CaseStage = new Dictionary<int, string>(); //阶段
        public static List<string> NoCheckToken = new List<string>(); //不检验token的action
        public static List<string> ManageNoCheckToken = new List<string>(); //不检验token的action
        public static string Timestamp = "";
        static Common()
        {
            NoCheckToken.AddRange(new string[] { "Login", "Login_Xcx", "Regist", "Send_SmsCode", "Back_Pwd", "Find_Home", "Find_NewsInfo", "Find_News", "Find_ParkByCarNum", "Find_ParkInfo", "Save_ParkSignNameOfH5", "Find_WxUserInfo" });
            ManageNoCheckToken.AddRange(new string[] { "Login" });
        }
        
        public static WxInfo GetWx()
        {
            string host = HttpContext.Current.Request.Url.Host;
            WxInfo wx = new WxInfo();
            if (host == "xipingzhifa.qiyedaishu.com")
            {
                wx.AppID = "wx4830c39f7e6e8277";
                wx.Secret = "73b167c4a2a049bac1225663a4176e33";
            }else
            {
                wx.AppID = "wx4830c39f7e6e8277";
                wx.Secret = "73b167c4a2a049bac1225663a4176e33";
            }
            return wx;
        }

        public static List<string> ToList(string str)
        {
            if (str == "")
            {
                return new List<string>();
            }
            else
            {
                return str.Split(',').ToList();
            }
        }
        public static string GetGrade(decimal Count)
        {
            string Grade = "环保新手";
            if(Count>=0 && Count < 200)
            {
                Grade = "环保新手";
            }
            if (Count >= 200 && Count < 500)
            {
                Grade = "环保侠客";
            }
            if (Count >= 500 && Count < 1000)
            {
                Grade = "环保骑士";
            }
            if (Count >= 1000 && Count < 2000)
            {
                Grade = "环保精灵";
            }
            if (Count >= 2000 && Count < 4000)
            {
                Grade = "环保使者";
            }
            if (Count >= 4000)
            {
                Grade = "环保天使";
            }
            return Grade;
        }
        public static int GetServerPwd()
        {
            Random rand = new Random();
            return rand.Next(1000, 9999);
        }
        //获取config文件value
        public static string GetConfig(string key)
        {
            if (!string.IsNullOrEmpty(key) &&
                ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                return ConfigurationManager.AppSettings[key].ToString();
            }
            return string.Empty;
        }
        /// <summary>
        /// 启动服务器应用程序
        /// </summary>
        public static void ReStartServer()
        {
            try
            {
                Process[] processes = Process.GetProcesses();
                foreach (Process p in processes)
                {
                    if (p.ProcessName == "House")
                    {
                        p.Kill();
                    }
                }
                System.Diagnostics.Process.Start("D:/www/houseserver/House.exe");
            }
            catch (Exception)
            {
            }
        }
        public static string CreateEwm(string text)
        {
            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
            QRCode qrcode = new QRCode(qrCodeData);

            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap bmp = null;
            string icon = "";
            if (!string.IsNullOrEmpty(icon))
            {
                bmp = new Bitmap(icon);
            }
            Bitmap qrCodeImage = qrcode.GetGraphic(10, Color.Black, Color.White, bmp, 15, 6, true);
            qrCodeImage = (Bitmap)qrCodeImage.GetThumbnailImage(300, 300, null, IntPtr.Zero);
            return ImgToBase64String(qrCodeImage);
        }
        public static string ImgToBase64String(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return "data:image/png;base64," + Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static void CreateEwm(string text, string path, string icon)
        {
            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
            QRCode qrcode = new QRCode(qrCodeData);

            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap bmp = null;
            if (!string.IsNullOrEmpty(icon))
            {
                bmp = new Bitmap(icon);
            }
            Bitmap qrCodeImage = qrcode.GetGraphic(10, Color.Black, Color.White, bmp, 15, 6, true);
            qrCodeImage = (Bitmap)qrCodeImage.GetThumbnailImage(300, 300, null, IntPtr.Zero);
            qrCodeImage.Save(path);
        }
        /// <summary>
        /// 过滤HTML
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FilterHTML(string str)
        {
            str = Regex.Replace(str, @"<[\s\S]*?>", "");
            return str.Replace("&nbsp;", "");
        }
        /// <summary>
        /// URL字符编码
        /// </summary>
        public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpContext.Current.Server.UrlEncode(str);
        }

        /// <summary>
        /// URL字符解码
        /// </summary>
        public static string UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetWebClientIP()
        {

            string userIP = "未获取用户IP";

            try
            {
                if (System.Web.HttpContext.Current == null
            || System.Web.HttpContext.Current.Request == null
            || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    return "";

                string CustomerIP = "";

                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (!String.IsNullOrEmpty(CustomerIP))
                    return CustomerIP;

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                return CustomerIP;
            }
            catch { }

            return userIP;

        }
        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”，估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];     //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;     //代理中的内容 非IP，取IP 
                    }
                }
                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];


                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;
                return result;
            }

        }
        /// <summary>
        /// 是否是IP地址格式
        /// </summary>
        /// <param name="str1"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        /// <summary>
        /// 获取星期
        /// </summary>
        /// <returns></returns>
        public static string GetWeek()
        {
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
        }
        /// <summary>
        /// 获取日期
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string getMonthDay(DateTime date)
        {
            string year_day = "";
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }

            return year_day;
        }
        public static string getMonthDayHourMinute(DateTime date)
        {
            string year_day = "";
            string minite = date.Minute.ToString();
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }
            if (minite.Length < 2)
            {
                minite = "0" + minite;
            }
            return year_day + date.Hour + ":" + minite;
        }
        /// <summary>
        /// 计算两个日期的时间间隔,返回的是时间间隔的日期差的绝对值.
        /// </summary>
        /// <param name="DateTime1">第一个日期和时间</param>
        /// <param name="DateTime2">第二个日期和时间</param>
        /// <returns></returns>
        public static int DateDiff(DateTime DateTime1, DateTime DateTime2, string Flag)
        {
            double dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                if (Flag == "Y")
                {
                    dateDiff = ts.TotalDays / 365;
                }
                else if (Flag == "D")
                {
                    dateDiff = ts.TotalDays;
                }
                else if (Flag == "H")
                {
                    dateDiff = ts.TotalHours;
                }
                else if (Flag == "M")
                {
                    dateDiff = ts.TotalMinutes;
                }
                else if (Flag == "S")
                {
                    dateDiff = ts.TotalSeconds;
                }

            }
            catch
            {
            }
            return DateTime1 < DateTime2 ? (int)dateDiff : -(int)dateDiff;
        }
        /// <summary>
        /// 读取Excel到DataTable
        /// </summary>
        /// <param name="pathName"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string pathName)
        {
            string sheetName = "Sheet1$";
            DataTable tbContainer = new DataTable();
            string strConn = string.Empty;
            FileInfo file = new FileInfo(pathName);
            if (!file.Exists) { throw new Exception("文件不存在"); }
            string extension = file.Extension;
            switch (extension)
            {
                case ".xls":
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
                case ".xlsx":
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    break;
                default:
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
            }
            //链接Excel
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            cnnxls.Open();
            DataTable FromExcel = cnnxls.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            if (FromExcel.Rows.Count >= 2)
            {
                sheetName = FromExcel.Rows[1]["TABLE_NAME"].ToString();
            }
            cnnxls.Close();
            //读取Excel里面有 表Sheet1
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}]", sheetName), cnnxls);
            DataSet ds = new DataSet();
            //将Excel里面有表内容装载到内存表中！
            oda.Fill(tbContainer);
            return tbContainer;
        }

        /// <summary>
        /// 获取CSV导入的数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileName">文件名称(.csv不用加)</param>
        /// <returns></returns>
        public static DataTable CsvToDataTable(string filePath, string fileName)
        {
            string path = Path.Combine(filePath, fileName + ".csv");
            string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
            try
            {
                using (OdbcConnection odbcConn = new OdbcConnection(connString))
                {
                    odbcConn.Open();
                    OdbcCommand oleComm = new OdbcCommand();
                    oleComm.Connection = odbcConn;
                    oleComm.CommandText = "select * from [" + fileName + "#csv]";
                    OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds, fileName);
                    return ds.Tables[0];
                    odbcConn.Close();
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (Exception ex)
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                throw ex;
            }
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="str"></param>
        public static void Log(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.GetEncoding("utf-8"));//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        /// <summary>
        /// sign验证
        /// </summary>
        /// <returns></returns>
        public static bool CheckSign()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string action = JobRequest.GetRequestString("Act");
                string sign = JobRequest.GetRequestString("Sign");
                string timestamp = JobRequest.GetRequestString("Timestamp");
                sb.AppendFormat("Account={0}&Act={1}&Key={2}&Timestamp={3}", "ZongHeZhiFa_CLIENT", action, "465E2B86CE4F42A552C533078E5ADC5F", timestamp);
                string signstr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToLower();
                return sign == signstr;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public static string GetSign(string Act, string Timestamp)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Account={0}&Act={1}&Key={2}&Timestamp={3}", "ZongHeZhiFa_CLIENT", Act, "465E2B86CE4F42A552C533078E5ADC5F", Timestamp);
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToLower();
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        /// <summary>
        /// 截取指定长度字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string SubString(string str, int length)
        {
            str = FilterHTML(str);
            if (str.Length > length)
            {
                return str.Substring(0, length);
            }
            else
            {
                return str;
            }
        }
        /// <summary>
        /// 截取中英文混合字符串
        /// </summary>
        /// <param name="str">字符文本</param>
        /// <param name="length">截取长度</param>
        /// <returns></returns>
        public static string CutString(string str, int length)
        {
            str = FilterHTML(str);
            int strLength = 0;
            StringBuilder strb = new StringBuilder();
            char[] Temp = str.ToCharArray();
            for (int i = 0; i != Temp.Length; i++)
            {
                if (strLength >= length)
                {
                    strb.Append("...");
                    break;
                }
                else
                {
                    if (((int)Temp[i]) < 255) //大于255的都是汉字或者特殊字符
                    {
                        strLength++;
                    }
                    else
                    {
                        strLength = strLength + 2;
                    }
                    strb.Append(Temp[i]);
                }
            }
            return strb.ToString();
        }
        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <param name="head">前缀，比如:PO</param>
        /// <param name="num">单号</param>
        /// <returns></returns>
        public static string ToNum(string head, string userid, string num)
        {
            var newnum = "";
            var date = DateTime.Now.ToString("yyyyMMddHHmmss");
            if (string.IsNullOrEmpty(num))
            {
                newnum = head + userid + date + "0001";
            }
            else
            {
                if (num.Length >= 19)
                {
                    int maxnum = int.Parse(num.Substring(num.Length - 4, 4)) + 1;
                    newnum = head + userid + date + maxnum.ToString().PadLeft(4, '0');
                }
            }
            return newnum;
        }
        /// <summary>
        /// 给字符串两边添加逗号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string AddDou(string str)
        {
            return "," + str.Trim(',') + ",";
        }
        /// <summary>
        /// SQL关键词过滤
        /// </summary>
        /// <param name="InText"></param>
        /// <returns></returns>
        public static bool SqlFilter(string InText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// size大小只能为200,500,1000三种大小
        /// </summary>
        /// <param name="path"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GetImg(string path, int size)
        {
            string[] files = path.Split('.');
            string ext = "." + files[files.Length - 1];
            return path.Replace(ext, "") + "_" + size + ext;
        }

        public static string TranRN(string str)
        {
            return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>").Replace(" ", "&nbsp;");
        }
        public static string TranEmpty(object num)
        {
            return DataConvert.ToDecimal(num)==0?"":num.ToString();
        }
        public static string TranDate(DateTime date)
        {
            return date == DateHelper.DefaultDate ? "" : date.ToString("yyyy-MM-dd");
        }
        public static string TranDateStr(DateTime date)
        {
            return date == DateHelper.DefaultDate ? "" : date.ToString("yyyy年MM月dd日");
        }
        public static string TranMinuteStr(DateTime date)
        {
            return date == DateHelper.DefaultDate ? "" : date.ToString("yyyy年MM月dd日HH时mm分");
        }
        public static string TranDateTime(DateTime date)
        {
            return date == DateHelper.DefaultDate ? "" : date.ToString("yyyy-MM-dd HH:mm:ss");
        }
        public static string TranDateMinute(DateTime date)
        {
            return date == DateHelper.DefaultDate ? "" : date.ToString("yyyy-MM-dd HH:mm");
        }
        //字符编码转汉字
        public static string UnicodeToGB(string text)
        {
            System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})");
            if (mc != null && mc.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match m2 in mc)
                {
                    string v = m2.Value;
                    string word = v.Substring(2);
                    byte[] codes = new byte[2];
                    int code = Convert.ToInt32(word.Substring(0, 2), 16);
                    int code2 = Convert.ToInt32(word.Substring(2), 16);
                    codes[0] = (byte)code2;
                    codes[1] = (byte)code;
                    text = text.Replace(v, Encoding.Unicode.GetString(codes));
                }
            }
            else
            {

            }
            return text;
        }
        //ip地址转城市名
        public static string IpToAddress(string ip)
        {
            try
            {
                WeiXin wx = new WeiXin();
                string str = wx.HttpGet("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip, "");
                string unicode = UnicodeToGB(str);
                dynamic json = wx.ConvertJson(unicode);
                return json.data.region + json.data.city;
            }
            catch (Exception ex) { }
            return "";
        }

        //计算距离
        public static double CalcDistance(double fromX, double fromY, double toX, double toY)
        {
            double rad = 6371; //Earth radius in Km

            //Convert to radians

            double p1X = fromX / 180 * Math.PI;

            double p1Y = fromY / 180 * Math.PI;

            double p2X = toX / 180 * Math.PI;

            double p2Y = toY / 180 * Math.PI;

            return Math.Acos(Math.Sin(p1Y) * Math.Sin(p2Y) +

                Math.Cos(p1Y) * Math.Cos(p2Y) * Math.Cos(p2X - p1X)) * rad * 1000;
        }

        //获取Token
        public static string GetToken()
        {
            return Guid.NewGuid().ToString("N");
        }

        //检查时间戳是否过期
        public static bool OutTime(string timestamp)
        {
            long time1 = GetTimestamp()*10000;
            long time2 = long.Parse(timestamp) * 10000;
            TimeSpan nowTimeSpan = new TimeSpan(time1-time2);
            return nowTimeSpan.Minutes > 10 ? true : false;
        }
        //检查是否恶意请求
        public static bool BadRequest(string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    RedisHelper redis = new RedisHelper(1);
                    int count = 0;
                    string num = redis.StringGet(token);
                    if (!string.IsNullOrEmpty(num))
                    {
                        count = DataConvert.ToInt(num);
                    }
                    redis.StringSet(token, ++count, TimeSpan.FromSeconds(1));
                    if (count > 10)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }catch(Exception ex)
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        public static DateTime TimestampToDateTime(long timestamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = timestamp * 10000;
            TimeSpan nowTimeSpan = new TimeSpan(lTime);
            DateTime resultDateTime = dateTimeStart.Add(nowTimeSpan);
            return resultDateTime;
        }
        public static long GetTimestamp()
        {
            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
            return (long)ts.TotalMilliseconds;
        }
        public static string AESDecrypt(string inputdata, string AesIV, string AesKey)
        {
            AesIV = AesIV.Replace(" ", "+");
            AesKey = AesKey.Replace(" ", "+");
            inputdata = inputdata.Replace(" ", "+");
            byte[] encryptedData = Convert.FromBase64String(inputdata);
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Key = Convert.FromBase64String(AesKey); // Encoding.UTF8.GetBytes(AesKey); 
            rijndaelCipher.IV = Convert.FromBase64String(AesIV);// Encoding.UTF8.GetBytes(AesIV);
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            string result = Encoding.UTF8.GetString(plainText);
            return result;
        }
        /// <summary>
        /// 获取字符中指定标签的值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="title">标签</param>
        /// <returns>值</returns>
        public static string GetTagValue(string html, string tag)
        {
            string tmpStr = string.Format("<{0}[^>]*?>(?<Tag>[^<]*)</{0}>", tag); //获取<title>之间内容
            Match TitleMatch = Regex.Match(html, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["Tag"].Value;
            return result;
        }
        /// <summary>
        /// 根据标签ID获取html内容中的某块代码，包含本标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetTagByID(string html, string id)
        {
            // 获取前后对应的标记 如果是双引号，可以这样写：class=""left""
            Regex reg = new Regex(string.Format(@"(?is)<div id=""{0}""[^>]*>(?><div[^>]*>(?<o>)|</div>(?<-o>)|(?:(?!</?div\b).)*)*(?(o)(?!))</div>", id));
            Match first = reg.Match(html);
            string sss = first.Value;
            return first.Value;
        }
        /// <summary>
        /// 根据标签Class获取html内容中的某块代码，包含本标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetTagByClass(string html, string classes)
        {
            // 获取前后对应的标记 如果是双引号，可以这样写：class=""left""
            Regex reg = new Regex(string.Format(@"(?is)<div class=""{0}""[^>]*>(?><div[^>]*>(?<o>)|</div>(?<-o>)|(?:(?!</?div\b).)*)*(?(o)(?!))</div>", classes));
            Match first = reg.Match(html);
            string sss = first.Value;
            return first.Value;
        }
        /// <summary>
        /// 获取Element=tag的所有标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static List<string> GetTagList(string html, string tag)
        {
            MatchCollection list = Regex.Matches(html, string.Format(@"<{0}(\w|\W)*?<\/{0}>", tag), RegexOptions.IgnoreCase);
            List<string> slist = new List<string>();
            foreach (Match match in list)
            {
                slist.Add(match.Value);
            }
            return slist;
        }
        /// <summary>
        /// 根据标签Class获取html内容中的标签集合
        /// </summary>
        /// <param name="html"></param>
        /// <param name="tag"></param>
        /// <param name="classes"></param>
        /// <returns></returns>
        public static List<string> GetTagListByClass(string html, string tag, string classes)
        {
            MatchCollection list = Regex.Matches(html, string.Format(@"<{0} class=""{1}""(\w|\W)*?<\/{0}>", tag, classes), RegexOptions.IgnoreCase);
            List<string> slist = new List<string>();
            foreach (Match match in list)
            {
                slist.Add(match.Value);
            }
            return slist;
        }
        /// <summary>  
        /// 获取字符中指定标签的属性值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="title">标签</param>
        /// <param name="attrib">属性名</param>
        /// <returns>属性</returns>  
        public static string GetAttrValue(string html, string title, string attr)
        {
            string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<Attr>[^'\"\"\\s>]+)\\1[^>]*>", title, attr); //获取<title>之间内容  
            Match TitleMatch = Regex.Match(html, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["Attr"].Value;
            return result;
        }
        /// <summary>
        /// 提取文本内容中的url连接
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static List<string> GetUrlList(string html)
        {
            MatchCollection list = Regex.Matches(html, @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%#_\./-~-]*)?", RegexOptions.IgnoreCase);
            List<string> slist = new List<string>();
            foreach (Match match in list)
            {
                slist.Add(match.Value);
            }
            return slist;
        }
        /// <summary>
        /// 下载html内容中所有的图片到本地，此方法为公众号写法，若来源于其他内容，请自行修改代码
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string DownImg(string html)
        {
            WeiXin wx = new WeiXin();
            Regex regImg1 = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签)
            MatchCollection matches1 = regImg1.Matches(html);
            string fold = DateTime.Now.ToString("yyyy-MM-dd");
            string path = HttpContext.Current.Server.MapPath("/upload/" + fold);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            int count = 0;
            foreach (Match matches in matches1)
            {
                if (matches.Groups["imgUrl"].Value.StartsWith("http"))
                {
                    count++;
                    string img = matches.Groups["imgUrl"].Value;

                    string ext = "gif";
                    if (img.Split('=').Length >= 2)
                    {
                        ext = img.Split('=')[img.Split('=').Length - 1];
                    }
                    string file = "/upload/" + fold + "/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + count + "." + ext;
                    wx.SaveFile(img, file);
                    html = html.Replace(img, file);
                }
            }
            return html;
        }
        /// <summary>
        /// 获取html内容中所有的图片集合
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static List<string> GetImgList(string html)
        {
            List<string> list = new List<string>();
            Regex regImg1 = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签)
            MatchCollection matches1 = regImg1.Matches(html);
            foreach (Match matches in matches1)
            {
                string img = matches.Groups["imgUrl"].Value;
                list.Add(img);
            }
            return list;
        }
        public static string UploadImg()
        {
            var content = HttpContext.Current;
            string opath = "/upload/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var rootpath = content.Server.MapPath(opath);
            if (!System.IO.Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            string str = "";
            for (int j = 0; j < content.Request.Files.Count; j++)
            {
                HttpPostedFile uploadFile = content.Request.Files[j];
                if (uploadFile.ContentLength > 0)
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    string imgpath50 = name + "_50" + ext;
                    string imgpath100 = name + "_100" + ext;
                    string imgpath200 = name + "_200" + ext;
                    string imgpath500 = name + "_500" + ext;
                    string imgpath1000 = name + "_1000" + ext;
                    Thumbnail.MakeThumbnailImage(file, imgpath50, 50, 50);
                    Thumbnail.MakeThumbnailImage(file, imgpath100, 100, 100);
                    Thumbnail.MakeThumbnail(file, imgpath200, 200, 200);
                    Thumbnail.MakeThumbnailImage(file, imgpath500, 500, 500);
                    Thumbnail.MakeThumbnailImage(file, imgpath1000, 1000, 1000);
                    str = opath + unique + ext;
                }

            }
            return str;
        }
        /// <summary>
        /// 生成唯一单号
        /// </summary>
        /// <param name="str">前缀</param>
        /// <returns></returns>
        public static string GetNum(string str)
        {
            try
            {
                long time = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                long prev = System.Web.HttpRuntime.Cache.Get("num") == null ? time : (long)System.Web.HttpRuntime.Cache.Get("num") + 1;
                System.Web.HttpRuntime.Cache.Insert("num", prev, null, DateTime.Now.AddSeconds(1), TimeSpan.Zero);
                return str + prev;
            }
            catch (Exception ex)
            {
                return str + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            }
        }
        //把HTML转化为标准H5页面
        public static string ToH5(string str)
        {
            return "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name = \"format-detection\" content=\"telephone=no\" /><meta name=\"viewport\" content=\"width=device-width, minimum-scale = 1.0, maximum-scale = 1.0, initial-scale = 1.0, user-scalable = no\" /><style>img{width:100% !important;}</style></head><body>" + str + "</body></html>";
        }
        //过滤，。符号
        public static string FilterChar(string str)
        {
            str = str.Replace("\n", "").Replace("\r", "").Replace("\r\n", "").Replace(",", "，").Replace("，，", "，").Replace("。。", "。").Replace("。，", "。").Replace("，。", "。");
            if (str.EndsWith("."))
            {
                str = str.Replace(".", "。");
            }
            return str;
        }
        //获取指定日期是本年的第几周
        public static int WeekOfYear(DateTime now)
        {
            System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
            return gc.GetWeekOfYear(now, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
        }
        public static bool SendSms(string PhoneNumber, string TemplateParam, string TemplateCode)
        {
            if (PhoneNumber.Length != 11)
            {
                return false;
            }
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAIkLqQzpWM4gdh", "phu8jFkT7gVhE8iWqEimfOvRADXbYt");
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", PhoneNumber);
            request.AddQueryParameters("SignName", "西平县城市管理局");
            request.AddQueryParameters("TemplateCode", TemplateCode);
            request.AddQueryParameters("TemplateParam", TemplateParam);
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                string json = System.Text.Encoding.UTF8.GetString(response.HttpResponse.Content);
                WeiXin wx = new WeiXin();
                dynamic o = wx.ConvertJson(json);
                if (o.Message == "OK" && o.Code == "OK")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (ServerException e)
            {
                return false;
            }
            catch (ClientException e)
            {
                return false;
            }
        }
        
        
        


        //去除Script
        public static string NoScript(string Htmlstring)
        {
            return Regex.Replace(Htmlstring, @"<script([^>])*>(\w|\W)*?</script([^>])*>", "", RegexOptions.IgnoreCase);
        }
        //去除Css
        public static string NoCss(string Htmlstring)
        {
            return Regex.Replace(Htmlstring, @"<style([^>])*>(\w|\W)*?</style([^>])*>", "", RegexOptions.IgnoreCase);
        }
        public static string TranToWatchTime(decimal CurrentTime)
        {
            int Hour = 0, Minute=0, Second=0;
            if (CurrentTime >= 3600)
            {
                Hour = (int)CurrentTime / 3600;
                Minute = (int)CurrentTime / 60 % 60;
                Second = (int)CurrentTime % 60;
                return DateTime.Parse(Hour + ":" + Minute + ":" + Second).ToString("HH:mm:ss");
            }else
            {
                Minute = (int)CurrentTime / 60 % 60;
                Second = (int)CurrentTime % 60;
                return DateTime.Parse(Hour + ":" + Minute + ":" + Second).ToString("mm:ss");
            }
        }
        public static int TranToCurrentTime(string TimeLong)
        {
            string[] TimeLongs = TimeLong.Split(':');
            if (TimeLongs.Length==3)
            {
                return DataConvert.ToInt(TimeLongs[0])*3600+ DataConvert.ToInt(TimeLongs[1]) * 60 + DataConvert.ToInt(TimeLongs[2]);
            }
            else if (TimeLongs.Length == 2)
            { 
                return DataConvert.ToInt(TimeLongs[0]) * 60 + DataConvert.ToInt(TimeLongs[1]);
            }else
            {
                return 0;
            }
        }

        public static string Init_Str(string Default, params string[] Params)
        {
            string result = "";
            foreach(string param in Params)
            {
                if (param.Trim() != "")
                {
                    result = param;
                }
            }
            if (result.Trim() == "")
            {
                result = Default;
            }
            return result;
        }
        //删除相对路径下的文件
        public static void DeleteFile(string file)
        {
            try
            {
                string path = HttpContext.Current.Server.MapPath(file);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (Exception ex)
            {

            }
        }
        public static string Percent(decimal num)
        {
            if (num == 0)
            {
                return "";
            }
            string[] nums = num.ToString("0.00").Trim('0').Split('.');
            int length = nums[1].Length;
            if (length == 0)
            {
                return num.ToString("0");
            }
            if (length == 1)
            {
                return num.ToString("0.0");
            }
            if (length == 2)
            {
                return num.ToString("0.00");
            }
            return num.ToString();
        }

        public static void Exception(int id)
        {
            if (id == 0)
            {
                throw new Exception();
            }
        }
        public static void Exception(bool ok)
        {
            if (!ok)
            {
                throw new Exception();
            }
        }
        /// <summary>
        /// 截取左侧n个字符
        /// </summary>
        /// <param name="str">12345</param>
        /// <param name="length">5</param>
        public static string LeftStr(string str, int length)
        {
            int Count = 0;
            int Index = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (Char.IsDigit(str, i))
                {
                    Count++; //统计数字
                    Index++;
                }
                else if (Char.IsWhiteSpace(str, i))
                {
                    Count++;//统计空格
                    Index++;
                }
                else if (Char.ConvertToUtf32(str, i) >= Convert.ToInt32("4e00", 16) && Char.ConvertToUtf32(str, i) <= Convert.ToInt32("9fff", 16))
                {
                    Count += 2;
                    Index++;
                }
                else if (Char.IsLetter(str, i))
                {
                    Count++;//统计字母,包括汉字
                    Index++;
                }
                else
                {
                    Count += 2;
                    Index++;
                }
                if (Count >= length)
                {
                    break;
                }
            }
            if (str.Trim() == "")
            {
                return "";
            }
            else
            {
                return str.Substring(0, Index);
            }
        }
        /// <summary>
        /// 跳过左侧n个字符
        /// </summary>
        /// <param name="str">12345</param>
        /// <param name="length">5</param>
        public static string RightStr(string str, int length)
        {
            if (str.Trim() == "")
            {
                return "";
            }
            else
            {
                return str.Replace(LeftStr(str, length), "");
            }

        }
        public static string GetDateStr(DateTime date, string filter)
        {
            if (date==DateHelper.DefaultDate)
            {
                return "";
            }
            else
            {
                return date.ToString(filter);
            }
        }
        public static dynamic GetContact(string DepartIDs)
        {
            dynamic contact = new ExpandoObject();
            contact.RealName = "李永立";
            contact.Mobile = "0396-6259896";
            contact.Address = "河南省西平县南大街257号";
            return contact;
        }
        public static string GetCss()
        {
            string From = JobRequest.GetRequestString("From");
            if (string.IsNullOrEmpty(From))
            {
                return "";
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("<script type=\"text/javascript\" src=\"/js/jquery.min.js\"></script>");
                builder.Append("<script type=\"text/javascript\" src=\"/js/common.js?v=23\"></script>");
                builder.Append("<link type=\"text/css\" rel=\"stylesheet\" href=\"/css/sheet.css?v=8\"/>");
                builder.Append("<style>#print .title{font-weight:bold !important;} #print{width:100% !important; margin-top:150px;}</style>");
                return builder.ToString();
            }
        }
        public static string PatchSpace(string str)
        {
            if (str == "")
            {
                return "&nbsp; &nbsp; &nbsp;";
            }
            else
            {
                return str;
            }
        }
        public static String joinObjectMapValue(IDictionary<string, string> map, char connector)
        {
            map = AsciiDictionary(map);
            StringBuilder b = new StringBuilder();
            foreach (KeyValuePair<string, string> kv in map)
            {
                b.Append(kv.Key);
                b.Append('=');
                if (kv.Value != null)
                {
                    b.Append(kv.Value);
                }
                b.Append(connector);
            }


            return b.ToString().Substring(0, b.Length - 1);
        }
        public static IDictionary<string, string> AsciiDictionary(IDictionary<string, string> sArray)
        {
            IDictionary<string, string> asciiDic = new Dictionary<string, string>();
            string[] arrKeys = sArray.Keys.ToArray();
            Array.Sort(arrKeys, string.CompareOrdinal);
            foreach (var key in arrKeys)
            {
                string value = sArray[key];
                asciiDic.Add(key, value);
            }
            return asciiDic;
        }
        private static string[] strs = new string[]
                                 {
                                  "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                                  "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
                                 };
        /// <summary>
        /// 创建随机字符串
        /// </summary>
        /// <returns></returns>
        public static string CreateNonce_str()
        {
            Random r = new Random();
            var sb = new StringBuilder();
            var length = strs.Length;
            for (int i = 0; i < 15; i++)
            {
                sb.Append(strs[r.Next(length - 1)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 创建时间戳
        /// </summary>
        /// <returns></returns>
        public static long CreateTimestamp()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }
        /// <summary>
        /// Sha1
        /// </summary>
        /// <param name="orgStr"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string Sha1(string orgStr, string encode = "UTF-8")
        {
            var sha1 = new SHA1Managed();
            var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
            byte[] resultHash = sha1.ComputeHash(sha1bytes);
            string sha1String = BitConverter.ToString(resultHash).ToLower();
            sha1String = sha1String.Replace("-", "");
            return sha1String;
        }
    }
}
